package com.xiaolanshu.controller;

import com.xiaolanshu.entity.Goods;
import com.xiaolanshu.entity.Order;
import com.xiaolanshu.entity.ShoppingCart;
import com.xiaolanshu.interceptor.UserHolder;
import com.xiaolanshu.service.GoodsService;
import com.xiaolanshu.service.OrderService;
import com.xiaolanshu.service.UserService;
import com.xiaolanshu.vo.GoodsInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

@RestController
@Slf4j
@RequestMapping("/shopping")
public class ShoppingController  {

    @Autowired
    private GoodsService goodsService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private UserService userService;

    /**
     * 获取商品列表
     * @return
     */
    @GetMapping
    public ResponseEntity shoppingIndex(){

        //首页推荐视频，随机生成一组整数，根据这些整数查找笔记
        Random random = new Random();
        int[] array = new int[20]; // 创建一个长度为20的整型数组
        for (int i = 0; i < array.length; i++) {
            array[i] = random.nextInt(50) + 1; // 为每个元素赋值一个[1,50)之间的随机整数
        }
        //获取推荐商品列表
        List<Goods> recommendGoodsList = goodsService.recommendGoodsList(array);

        //获取所有商品列表
        List<Goods> goodsList = goodsService.goodsList();

        //将推荐商品列表和所有商品列表保存到集合里
        Map<String,List<Goods>> goodsMap = new HashMap<>();
        goodsMap.put("推荐商品",recommendGoodsList);
        goodsMap.put("所有商品",goodsList);

        return ResponseEntity.ok(goodsMap);
    }

    /**
     * 获取商品内容
     * @param goodsId
     * @return
     */
    @GetMapping("/content/{goodsId}")
    public ResponseEntity goodsContent(@PathVariable Long goodsId){

        GoodsInfoVo goodsInfoVo = goodsService.findGoodsVoById(goodsId);
        return ResponseEntity.ok(goodsInfoVo);
    }

    /**
     * 根据商品名，标签，商品介绍模糊查询
     * @param param
     * @return
     */
    @GetMapping("/search")
    public ResponseEntity search(String param){
        //根据商品名，标签，商品介绍模糊查询
        List<Goods> goodsList = goodsService.search(param);
        return ResponseEntity.ok(goodsList);

    }

    /**
     * 商品直接结算
     * 如果是从笔记博主的引导链接直接结算，笔记博主也会获得一部分返利
     * @param param
     * @return
     */
    @PostMapping("/settle")
    public ResponseEntity settle(@RequestBody Map param){

        //从线程当中获取用户id（拦截器从请求头获取了用户信息并缓存到线程当中）
        Long userId = UserHolder.getUserId();

        Long goodsId =Long.valueOf((String) param.get("goodsId"));
        Double price = Double.valueOf((String) param.get("price"));
        Integer count = Integer.valueOf((String) param.get("count"));
        //如果是从笔记引导链接直接购物的，参数带有笔记博主的id
        Long noteUserId = null;
        if(param.get("userId")!=null){
           noteUserId  = Long.valueOf((String) param.get("userId"));
        }

        //根据商品id获取笔记信息
        Goods goods = goodsService.findGoods(goodsId);
        //获取商品返利率
        Double returnRate = goods.getReturnRate();
        //获取商品成本
        Double cost = goods.getCost();
        //计算商品总金额
        Double amount = price*count;
        //计算商品总成本
        Double costs = cost*count;

        //计算返利金额并保留2位小数
        DecimalFormat df=new DecimalFormat("0.00");
        Double returnAmount = Double.valueOf(df.format(amount*returnRate));
        //如果带有笔记博主id，则给笔记博主返利
        Double noteUserReturnAmount = null;
        if (noteUserId != null){
             noteUserReturnAmount = Double.valueOf(df.format(amount*0.1));
            //给笔记博主返利
            userService.saveReturnAmount(noteUserReturnAmount,noteUserId);
        }

        //结算时将上述商品信息保存到订单表
        Order order = new Order();
        order.setGoodsId(goodsId);
        order.setUserId(userId);
        order.setGoodsName(goods.getGoodsName());
        order.setCount(count);
        order.setPicture(goods.getPicture());
        order.setAmount(amount);
        order.setCost(costs);
        order.setPrice(goods.getPrice());
        //如果有给笔记博主返利，需将这一部分也加上
        if(noteUserReturnAmount != null){
            order.setReturnAmount(returnAmount+noteUserReturnAmount);
        }
        else
            order.setReturnAmount(returnAmount);
        //保存到表
        orderService.goodsSettle(order);

        //根据商品总金额扣除用户的余额
        userService.reduceMoney(amount,userId);
        //将所有返利金额保存到购买的用户的信息里
        userService.saveReturnAmount(returnAmount,userId);

        return ResponseEntity.status(200).body("结算成功");
    }

}
